package com.shoesmail.filter;

import com.alibaba.fastjson.JSON;
import com.shoesmail.annotation.JwtToken;
import com.shoesmail.domain.vo.JsonResultVo;
import com.shoesmail.enums.RoleEnum;
import com.shoesmail.utils.JwtUtil;
import com.shoesmail.utils.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author ：CDB
 * @description：通过注解的权限拦截器
 * @date ：2025/9/17 9:15
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查有没有需要用户权限的注解
        // 拓展：在注解中加数据即权限，在这拿到角色，然后执行对应操作
        if (method.isAnnotationPresent(JwtToken.class)) {
            JwtToken jwtToken = method.getAnnotation(JwtToken.class);
            if (jwtToken.required()) {
                // 执行认证
                if (token == null) {
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    httpServletResponse.getWriter().write(JSON.toJSONString(JsonResultVo.fail(401,"请登陆")));
                    return false;
                }

                //添加注解的方法，将token中的role与注解中的role做比较来实现
                // 获取 token 中的 userId
                String userId = JwtUtil.getUserId(token);

                RoleEnum role = JwtUtil.getRole(token);
                RoleEnum needRole = jwtToken.role();
                if(!role.equals(needRole)){
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    httpServletResponse.getWriter().write(JSON.toJSONString(JsonResultVo.fail(402,"权限不足")));
                    return false;
                }

                UserContext.setUserId(userId);
                //System.out.println("用户id:" + userId);
                // 验证 token
                JwtUtil.checkSign(token);
            }
        }
        return true;
    }
}
